package com.junzhiit.nengji.api.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bainaeco.framework.util.serializer.Format;
import com.junzhiit.nengji.api.service.RebateService;
import com.junzhiit.nengji.api.web.exception.RebateCategoryNotFoundException;
import com.junzhiit.nengji.api.web.exception.RebateCompleteErrorException;
import com.junzhiit.nengji.api.web.exception.RebateErrorException;
import com.junzhiit.nengji.api.web.exception.UserNotFoundException;
import com.junzhiit.nengji.api.web.vo.RebateInfoVO;
import com.junzhiit.nengji.api.web.vo.RebateVO;
import com.junzhiit.nengji.api.web.vo.ResultVO;
import com.junzhiit.nengji.bo.RebateInfoBO;
import com.junzhiit.nengji.dao.OrdersGoodsDAO;
import com.junzhiit.nengji.dao.RebateCategoryDAO;
import com.junzhiit.nengji.dao.RebateInfoDAO;
import com.junzhiit.nengji.dao.SystemConfigDAO;
import com.junzhiit.nengji.dao.UserConfigDAO;
import com.junzhiit.nengji.dao.cache.UserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.OrdersGoods;
import com.junzhiit.nengji.model.RebateCategory;
import com.junzhiit.nengji.model.RebateInfo;
import com.junzhiit.nengji.model.SystemConfig;
import com.junzhiit.nengji.model.UserConfig;
import com.junzhiit.nengji.model.enums.Is;

@Service
public class RebateServiceImpl extends BaseServiceImpl implements RebateService {

	@Autowired
	private SystemConfigDAO systemConfigDAO;
	
	@Autowired
	private UserCacheDAO userCacheDAO;
	
	@Autowired
	private RebateInfoDAO rebateInfoDAO;
	
	@Autowired
	private RebateCategoryDAO rebateCategoryDAO;
	
	@Autowired
	private UserConfigDAO userConfigDAO;
	
	@Autowired
	private OrdersGoodsDAO ordersGoodsDAO;
	
	@Override
	public RebateInfo addRebate(RebateVO rebateVO) {
		SystemConfig systemConfig = systemConfigDAO.find();
		if(systemConfig.getIsOpenRebate() == Is.YES.toIntValue()){
			RebateCategory rebateCategory = rebateCategoryDAO.getRebatePriceScope(rebateVO.getPrice());
			if(rebateCategory == null){
				throw new RebateCategoryNotFoundException("找不到返利队列");
			}
			Long index = userCacheDAO.incr(DIYKey.getRebateStringKey(rebateCategory.getId()));
			int userCode = index.intValue();
			RebateInfo rebateInfo = new RebateInfo();
			rebateInfo.setUserCode(userCode);
			int maxCode = rebateInfoDAO.getRebatInfoEndCode(rebateCategory.getId());
			rebateInfo.setStartCode(maxCode+1);
			rebateInfo.setEndCode(systemConfig.getRebateParameter()*userCode+1);
			rebateInfo.setShopId(rebateVO.getShopId());
			rebateInfo.setGoodsId(rebateVO.getGoodsId());
			rebateInfo.setUserId(rebateVO.getUserId());
			rebateInfo.setStatus(Is.NO.toIntValue());
			rebateInfo.setGoodsPrice(rebateVO.getPrice());
			rebateInfo.setGoodsName(rebateVO.getGoodsName());
			rebateInfo.setRebateCategoryId(rebateCategory.getId());
			rebateInfo.setOrderId(rebateVO.getOrderId());
			rebateInfo.setOrderGoodsId(rebateVO.getOrderGoodsId());
			RebateInfo params = rebateInfoDAO.insert(rebateInfo);
			return params;
		}
		return null;
	}

	@Override
	public ResultVO updateRedate(RebateInfo rebateInfo) {
		ResultVO result = new ResultVO();
		RebateInfo info = rebateInfoDAO.getRebatInfo(rebateInfo.getRebateCategoryId(), rebateInfo.getUserCode());
		if(info != null){
			if(info.getStatus() == Is.YES.toIntValue() || info.getEndCode() < rebateInfo.getUserCode()){
				throw new RebateCompleteErrorException("返利已完成");
			}
			Integer endCode = info.getEndCode();
			Integer userCode = rebateInfo.getUserCode();
			if(endCode.intValue() == userCode.intValue() ){
				info.setStatus(Is.YES.toIntValue());
				info.setCompleteTime(new Date());
			}
			SystemConfig systemConfig = systemConfigDAO.find();
			Double price = Format.decimal(rebateInfo.getGoodsPrice()/systemConfig.getRebateParameter());
			info.setRebatePrice(Format.decimal(info.getRebatePrice()+price));
			info.setRebateCode(rebateInfo.getUserCode());
			boolean is = rebateInfoDAO.update(info);
			if(!is){
				throw new RebateErrorException("返利失败");
			}
			UserConfig userConfig = userConfigDAO.getUserConfig(info.getUserId());
//			userConfig.setRebateMoney(userConfig.getRebateMoney()+price);
			userConfig.setWithdrawalMoney(userConfig.getWithdrawalMoney()+price);
			userConfigDAO.update(userConfig);
			
			OrdersGoods ordersGoods = ordersGoodsDAO.query(rebateInfo.getOrderGoodsId());
			ordersGoods.setIsQueue(Is.YES.toIntValue());
			ordersGoodsDAO.update(ordersGoods);
		}
		return result;
	}

	@Override
	public ResultVO getRebate(String userId) {
		ResultVO result = new ResultVO();
		if(!StringUtils.isNotEmpty(userId)){
			throw new UserNotFoundException("用户不存在");
		}
		List<RebateInfoBO> list = rebateInfoDAO.getRebatInfoByUserId(userId);
		List<RebateInfoVO> outListVO = new ArrayList<RebateInfoVO>();
		List<RebateInfoVO> notListVO = new ArrayList<RebateInfoVO>();
		int count = 0;
		double money = 0.0;
		for(RebateInfoBO rebateInfoBO : list){
			if(rebateInfoBO.getStatus() == Is.YES.toIntValue()){
				RebateInfoVO rebateInfoVO = new RebateInfoVO();
				BeanUtils.copyProperties(rebateInfoBO, rebateInfoVO);
				outListVO.add(rebateInfoVO);
				money+=rebateInfoBO.getRebatePrice();
			}else{
				RebateInfoVO rebateInfoVO = new RebateInfoVO();
				BeanUtils.copyProperties(rebateInfoBO, rebateInfoVO);
				notListVO.add(rebateInfoVO);
				count++;
			}
		}
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("outOrder", outListVO);
		map.put("notOrder", notListVO);
		map.put("goodsCount", count);
		map.put("countMoney", Format.decimal(money));
		result.setData(map);
		return result;
	}
	
	@Override
	public ResultVO updateAllRebate(){
		ResultVO result = new ResultVO();
		List<RebateInfoBO> list = rebateInfoDAO.updateRebate();
		for(RebateInfoBO rebateInfoBO : list){
			if(rebateInfoBO.getIsOpenRebate() == Is.YES.toIntValue()){
				for(int i = 0;i<rebateInfoBO.getNumber();i++){
					RebateVO rebateVO = new RebateVO();
					if(rebateInfoBO.getIsOpenSku() == Is.NO.toIntValue()){
						rebateVO.setPrice(rebateInfoBO.getGoodsPrice());
					}else if(rebateInfoBO.getIsOpenSku() == Is.YES.toIntValue()){
						rebateVO.setPrice(rebateInfoBO.getSkuPrice());
					}
					rebateVO.setGoodsId(rebateInfoBO.getGoodsId());
					rebateVO.setShopId(rebateInfoBO.getShopId());
					rebateVO.setGoodsName(rebateInfoBO.getGoodsName());
					rebateVO.setUserId(rebateInfoBO.getUserId());
					rebateVO.setOrderId(rebateInfoBO.getOrderId());
					rebateVO.setOrderGoodsId(rebateInfoBO.getOrderGoodsId());
					RebateInfo rebateInfo = addRebate(rebateVO);
					if(StringUtils.isNoneBlank(rebateInfo.getId())){
						updateRedate(rebateInfo);
					}
				}
			}
		}
		return result;
	}
}
